/*******************************************************************************
 * $Header$
 * $Revision$
 * $Date$
 *
 *==============================================================================
 *
 * Copyright©hxlife/hulife 
 * All rights reserved.
 * 
 * Created on 2017年9月20日
 *******************************************************************************/

package com.hualife.md.member.api;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.hualife.md.constants.APIConstants;
import com.hualife.md.constants.MDConstants;
import com.hualife.md.member.dao.ex.entity.MemberIntegrateInfo;
import com.hualife.md.member.dao.mybatis.entity.MemberInfo;
import com.hualife.md.member.dao.mybatis.entity.OrganizationInfo;
import com.hualife.md.member.dao.mybatis.entity.SynLisLaagent;
import com.hualife.md.member.dto.MemberQueryRequestDTO;
import com.hualife.md.member.dto.MemberQueryResponseDTO;
import com.hualife.md.member.dto.MembersFulltextQueryRequestDTO;
import com.hualife.md.member.dto.MembersFulltextQueryResponseDTO;
import com.hualife.md.member.dto.MembersInfoDTO;
import com.hualife.md.member.dto.MembersInfoResponseDTO;
import com.hualife.md.member.dto.OrganizationInfoDTO;
import com.hualife.md.member.dto.OrganizationsQueryRequestDTO;
import com.hualife.md.member.dto.OrganizationsQueryResponseDTO;
import com.hualife.md.member.dto.SubOrganizationDTO;
import com.hualife.md.member.service.IMemberQueryService;
import com.hualife.support.exception.BusinessException;
import com.hualife.support.exception.SysException;
import com.hualife.support.util.JsonUtil;

/**
 * @description: TODO 此处填写 class 信息
 * @author 孙小冬 (mailto:sunxiaodong001@hualife.cc)
 */
@RestController
@RequestMapping(value = "/api/v1")
public class MemberController {
	private static final Logger logger = LoggerFactory
			.getLogger(MemberController.class);

	@Autowired
	private IMemberQueryService memberQueryService;

	@RequestMapping(value = "/member/query", method = RequestMethod.GET)
	public Map<String, Object> memberQuery(HttpServletRequest request,
			HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*"); // 解决前后端跨域问题
		String data = request.getParameter("data");
		if (data == null || "".equals(data.trim()))
			throw new BusinessException("查询条件不允许为空！");

		try {
			MemberQueryRequestDTO requestDTO = (MemberQueryRequestDTO) JsonUtil
					.SnakeJson2CamelBean(data, MemberQueryRequestDTO.class);
			MemberInfo member = new MemberInfo();
			member.setMemberId(requestDTO.getMemberId());
			MemberIntegrateInfo memberInfo = memberQueryService
					.queryMemberInfo(member);
			if (memberInfo == null) {
				throw new BusinessException("查不到该用户信息！");
			}
			MemberQueryResponseDTO responseDTO = new MemberQueryResponseDTO();
			responseDTO.setMemberId(memberInfo.getMemberId());
			responseDTO.setMemberName(memberInfo.getMemberName());
			responseDTO.setOrganizationUnit(memberInfo.getOrganizationUnit());
			responseDTO.setOrganizationCode(memberInfo.getOrganizationCode());
			responseDTO.setOrganizationName(memberInfo.getOrganizationName());
			responseDTO.setOrganizationShortname(memberInfo
					.getOrganizationShortname());
			responseDTO.setAffiliationCode(memberInfo.getAffiliationCode());
			responseDTO.setAffiliationName(memberInfo.getAffiliationName());
			responseDTO.setDepartment(memberInfo.getDepartment());
			responseDTO.setTitle(memberInfo.getTitle());
			responseDTO.setEmail(memberInfo.getEmail());
			responseDTO.setState(memberInfo.getState());

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("result_code", APIConstants.RESULT_SUCCESS);
			map.put("result_message", "查询成功！");
			map.put("data", JsonUtil.CamelBean2SnakeJson(responseDTO));
			return map;
		} catch (JsonParseException e) {
			e.printStackTrace();
			logger.error("/api/v1/member/query交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		} catch (JsonMappingException e) {
			e.printStackTrace();
			logger.error("/api/v1/member/query交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("/api/v1/member/query交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		}

	}

	@RequestMapping(value = "/organizations/query", method = RequestMethod.GET)
	public Map<String, Object> organizationsQuery(HttpServletRequest request,
			HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*"); // 解决前后端跨域问题
		String data = request.getParameter("data");
		if (data == null || "".equals(data.trim()))
			throw new BusinessException("查询条件不允许为空！");

		try {
			OrganizationsQueryRequestDTO requestDTO = (OrganizationsQueryRequestDTO) JsonUtil
					.SnakeJson2CamelBean(data,
							OrganizationsQueryRequestDTO.class);
			if (requestDTO.getOrganizationCode() == null
					|| "".equals(requestDTO.getOrganizationCode().trim()))
				throw new BusinessException("查询条件不允许为空！");
			String organizationCode = requestDTO.getOrganizationCode().trim();
			OrganizationsQueryResponseDTO responseDTO = new OrganizationsQueryResponseDTO();
			OrganizationInfoDTO organizationInfo = new OrganizationInfoDTO();
			organizationInfo.setOrganizationCode(organizationCode);
			OrganizationInfo organization = new OrganizationInfo();
			organization.setOrganizationCode(organizationCode);
			OrganizationInfo organizationResult = memberQueryService
					.queryOrganizationInfo(organization);
			if (organizationResult != null) {
				organizationInfo.setOrganizationName(organizationResult
						.getOrganizationName());
				organizationInfo.setOrganizationShortname(organizationResult
						.getOrganizationShortname());
				organizationInfo.setAffiliationCode(organizationResult
						.getAffiliationCode());
				organizationInfo.setAffiliationName(organizationResult
						.getAffiliationName());
			} else {
				throw new BusinessException("查不到该机构信息！");
			}

			if ("0".equals(organizationResult.getCategory())) { // 内勤
				MemberInfo member = new MemberInfo();
				member.setOrganizationCode(organizationCode);
				List<MemberInfo> memberInfoResultList = memberQueryService
						.queryMemberInfos(member);
				List<MembersInfoDTO> membersInfoDTOList = new ArrayList<MembersInfoDTO>();
				for (MemberInfo memberInfoResult : memberInfoResultList) {
					MembersInfoDTO membersInfoDTO = new MembersInfoDTO();
					membersInfoDTO.setMemberId(memberInfoResult.getMemberId());
					membersInfoDTO.setMemberName(memberInfoResult
							.getMemberName());
					membersInfoDTO.setOrganizationUnit(memberInfoResult
							.getOrganizationUnit());
					membersInfoDTO.setDepartment(memberInfoResult
							.getDepartment());
					membersInfoDTO.setTitle(memberInfoResult.getTitle());
					membersInfoDTO.setEmail(memberInfoResult.getEmail());
					membersInfoDTO.setState(memberInfoResult.getState());
					membersInfoDTOList.add(membersInfoDTO);
				}

				organizationInfo.setMembersInfo(membersInfoDTOList);
			} else {
				SynLisLaagent laagent = new SynLisLaagent();
				laagent.setAgentgroup(organizationCode);
				List<SynLisLaagent> laagentResultList = memberQueryService
						.queryLaagentInfos(laagent);
				List<MembersInfoDTO> membersInfoDTOList = new ArrayList<MembersInfoDTO>();
				for (SynLisLaagent laagentResult : laagentResultList) {
					MembersInfoDTO membersInfoDTO = new MembersInfoDTO();
					membersInfoDTO.setMemberId(laagentResult.getAgentcode());
					membersInfoDTO.setMemberName(laagentResult.getName());
					membersInfoDTO.setOrganizationUnit(organizationResult
							.getWholeOrganizationName());
					membersInfoDTO.setState("0");
					membersInfoDTOList.add(membersInfoDTO);
				}

				organizationInfo.setMembersInfo(membersInfoDTOList);
			}

			responseDTO.setOrganizationInfo(organizationInfo);

			List<SubOrganizationDTO> subOrganizationList = new ArrayList<SubOrganizationDTO>();
			List<OrganizationInfo> organizationListResult = memberQueryService
					.querySubOrganizationInfos(organizationResult);
			for (OrganizationInfo subOrganizationResult : organizationListResult) {
				SubOrganizationDTO subOrganization = new SubOrganizationDTO();
				subOrganization.setOrganizationCode(subOrganizationResult
						.getOrganizationCode());
				subOrganization.setOrganizationName(subOrganizationResult
						.getOrganizationName());

				StringBuilder sb = new StringBuilder();
				sb.append(subOrganizationResult.getAffiliationCode())
						.append(MDConstants.SEPARATOR_DOT)
						.append(subOrganizationResult.getOrganizationCode());
				int totalNumber = memberQueryService
						.queryTotalMembersByAffiliation(sb.toString());
				subOrganization.setTotalNumber(totalNumber);
				subOrganizationList.add(subOrganization);
			}
			responseDTO.setSubOrganization(subOrganizationList);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("result_code", APIConstants.RESULT_SUCCESS);
			map.put("result_message", "查询成功！");
			map.put("data", JsonUtil.CamelBean2SnakeJson(responseDTO));
			return map;
		} catch (JsonParseException e) {
			e.printStackTrace();
			logger.error("/api/v1/organizations/query交易处理失败，原因是【{}】.",
					e.getMessage());
			throw new SysException(e.getMessage());
		} catch (JsonMappingException e) {
			e.printStackTrace();
			logger.error("/api/v1/organizations/query交易处理失败，原因是【{}】.",
					e.getMessage());
			throw new SysException(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("/api/v1/organizations/query交易处理失败，原因是【{}】.",
					e.getMessage());
			throw new SysException(e.getMessage());
		}
	}

	@RequestMapping(value = "/members/fulltext/query", method = RequestMethod.GET)
	public Map<String, Object> membersFulltextQuery(HttpServletRequest request,
			HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*"); // 解决前后端跨域问题
		String data = request.getParameter("data");
		if (data == null || "".equals(data.trim()))
			throw new BusinessException("查询条件不允许为空！");

		try {
			MembersFulltextQueryRequestDTO requestDTO = (MembersFulltextQueryRequestDTO) JsonUtil
					.SnakeJson2CamelBean(data,
							MembersFulltextQueryRequestDTO.class);
			List<MemberIntegrateInfo> memberInfoResultList = memberQueryService
					.queryMemberIntegrateInfos(requestDTO.getSearchTerms(),
							requestDTO.getSearchOperator());
			if (memberInfoResultList == null || memberInfoResultList.size() == 0) {
				throw new BusinessException("查不到用户信息！");
			} else if (memberInfoResultList.size() > 20) {
				throw new BusinessException("已匹配结果过多，请输入更多的查询条件以减少检索结果！");
			}
			MembersFulltextQueryResponseDTO responseDTO = new MembersFulltextQueryResponseDTO();
			List<MembersInfoResponseDTO> membersInfoDTOList = new ArrayList<MembersInfoResponseDTO>();
			for (MemberIntegrateInfo memberInfoResult : memberInfoResultList) {
				MembersInfoResponseDTO membersInfoDTO = new MembersInfoResponseDTO();
				membersInfoDTO.setMemberId(memberInfoResult.getMemberId());
				membersInfoDTO.setMemberName(memberInfoResult.getMemberName());
				membersInfoDTO.setOrganizationUnit(memberInfoResult.getOrganizationUnit());
				membersInfoDTO.setOrganizationCode(memberInfoResult.getOrganizationCode());
				membersInfoDTO.setOrganizationName(memberInfoResult.getOrganizationName());
				membersInfoDTO.setOrganizationShortname(memberInfoResult
						.getOrganizationShortname());
				membersInfoDTO.setAffiliationCode(memberInfoResult.getAffiliationCode());
				membersInfoDTO.setAffiliationName(memberInfoResult.getAffiliationName());
				membersInfoDTO.setDepartment(memberInfoResult.getDepartment());
				membersInfoDTO.setTitle(memberInfoResult.getTitle());
				membersInfoDTO.setEmail(memberInfoResult.getEmail());
				membersInfoDTO.setState(memberInfoResult.getState());
				membersInfoDTOList.add(membersInfoDTO);
			}
			responseDTO.setMembersInfo(membersInfoDTOList);

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("result_code", APIConstants.RESULT_SUCCESS);
			map.put("result_message", "查询成功！");
			map.put("data", JsonUtil.CamelBean2SnakeJson(responseDTO));
			return map;
		} catch (JsonParseException e) {
			e.printStackTrace();
			logger.error("/api/v1/member/query交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		} catch (JsonMappingException e) {
			e.printStackTrace();
			logger.error("/api/v1/member/query交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("/api/v1/member/query交易处理失败，原因是【{}】.", e.getMessage());
			throw new SysException(e.getMessage());
		}

	}
}

/*
 * 修改历史 $Log$
 */